package com.lujianfei.gamelearn.mahjong

import MahjongModel
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Paint
import android.graphics.Rect
import android.util.Log
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.ElevatedButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.graphics.drawscope.drawIntoCanvas
import androidx.compose.ui.graphics.nativeCanvas
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.TextMeasurer
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.rememberTextMeasurer
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.lujianfei.gamelearn.MyApplication
import com.lujianfei.gamelearn.R
import com.lujianfei.gamelearn.utils.DensityUtils
import androidx.lifecycle.viewmodel.compose.viewModel

private val resultWidth = DensityUtils.dpToPx(230f)
/**
 * Author: lujianfei
 * Date: 2025/2/5 19:02
 * Description:
 */
@Composable
fun MahjongCanvas(modifier: Modifier = Modifier) {
    val viewModel:MahjongViewModel = viewModel()
    LaunchedEffect(Unit) {
        viewModel.init()
    }

    val textMeasurer = rememberTextMeasurer()
    // 获取屏幕配置
    val configuration = LocalConfiguration.current
    // 获取屏幕宽度（dp）
    val screenWidthDp = configuration.screenWidthDp
    // 获取屏幕高度（dp）
    val screenHeightDp = configuration.screenHeightDp
    // 获取当前的Density
    val density = LocalDensity.current.density

    // 将宽度从 dp 转换为 px
    val screenWidthPx = (screenWidthDp * density).toInt()
    val screenHeightPx = (screenHeightDp * density).toInt()

    Box {
        Canvas(
            modifier = modifier
                .fillMaxWidth()
                .fillMaxHeight()
                .pointerInput(Unit) {
                    detectTapGestures { offset ->
                        // 在这里处理点击事件
                        // offset 是点击位置的坐标
                        Log.d("GameCanvas", "Clicked at: ${offset.x}, ${offset.y}")
                        viewModel.touchOn(offset)
                    }
                }
            , onDraw = onDraw(textMeasurer, viewModel = viewModel, screenWidthPx = screenWidthPx, screenHeightPx = screenHeightPx)
        )

        if (viewModel.hasSelected()) {
            ElevatedButton(modifier = Modifier
                .align(Alignment.CenterEnd)
                .padding(end = 15.dp), onClick = {
                viewModel.play()
            }) {
                // 按钮文本
                Text("出牌")
            }
        }
        if (viewModel.questionAnswerResult.value != null) {
            val result = viewModel.questionAnswerResult.value!!
            ShowResult(modifier = modifier.align(Alignment.CenterEnd), title = result.title,
                answer = result.answer, content = result.content, isCorrect = result.isCorrect, onConfirm = {
                    viewModel.next()
                })
        }

        Text(text = "题${viewModel.questionIndex.value + 1}.优先打哪张牌最优？", color = Color.White, fontSize = 30.sp, modifier = Modifier
            .align(
                Alignment.TopCenter
            )
            .padding(top = 40.dp))
    }
}

@Composable
private fun onDraw(
    textMeasurer: TextMeasurer,
    viewModel: MahjongViewModel,
    screenWidthPx: Int,
    screenHeightPx: Int
): DrawScope.() -> Unit = {
    // 加载麻将素材图像
    val originalImage = BitmapFactory.decodeResource(MyApplication.instance.resources, R.drawable.majiang_full)
//        val eachWidth = 110
//        val eachHeight = 155
//        val paddingStart = 10
//        val gap = 22
//        var top = 0
//
//        for (i in 0 until 9) {
//            val left = paddingStart + i * (eachWidth + gap)
//            val right = left + eachWidth
//            val bottom = top + eachHeight
//            extracted(this, originalImage, left, top, right, bottom)
//        }
//
//        top += eachHeight
//        for (i in 0 until 9) {
//            val left = paddingStart + i * (eachWidth + gap)
//            val right = left + eachWidth
//            val bottom = top + eachHeight
//            extracted(this, originalImage, left, top, right, bottom)
//        }
//
//        top += eachHeight
//        for (i in 0 until 9) {
//            val left = paddingStart + i * (eachWidth + gap)
//            val right = left + eachWidth
//            val bottom = top + eachHeight
//            extracted(this, originalImage, left, top, right, bottom)
//        }
//
//        top += eachHeight
//        for (i in 0 until 7) {
//            val left = paddingStart + i * (eachWidth + gap)
//            val right = left + eachWidth
//            val bottom = top + eachHeight
//            extracted(this, originalImage, left, top, right, bottom)
//        }
    drawPaiList(this, originalImage, viewModel, screenWidthPx = screenWidthPx, screenHeightPx = screenHeightPx)
    drawPaiOutList(this, originalImage, viewModel, screenWidthPx = screenWidthPx, screenHeightPx = screenHeightPx)
}

private fun extracted(drawScope: DrawScope, originalImage: Bitmap, left:Int, top:Int, right:Int, bottom:Int) {
    // 要截取的区域
    val srcRect = Rect(left, top, right, bottom) // 根据您的麻将图像调整此区域
    val dstRect = Rect(left, top, right, bottom) // 绘制到画布上的目标区域

    // 创建一个画笔
    val paint = Paint()
    // 在Canvas上绘制截取的图像
    drawScope.drawIntoCanvas { canvas ->
        canvas.nativeCanvas.drawBitmap(originalImage, srcRect, dstRect, paint)
    }
}

/**
 * 绘制麻将列表
 */
private fun drawPaiList(
    drawScope: DrawScope,
    originalImage: Bitmap,
    viewModel: MahjongViewModel,
    screenWidthPx: Int,
    screenHeightPx: Int
) {
    val totalWidth = viewModel.mahjongList.sumOf { it.drawInfo.srcRect.width() }
    val width = viewModel.mahjongList.firstOrNull()?.drawInfo?.srcRect?.width()?:0
    val height = viewModel.mahjongList.firstOrNull()?.drawInfo?.srcRect?.height()?:0

    // 水平居中排列
    var startX =  (screenWidthPx - totalWidth) / 2
    val startY = screenHeightPx - height - 200

    // 如果结果已经出来挡住了牌面，需要做调整
    if (viewModel.questionAnswerResult.value !=null && (startX + totalWidth) > (screenWidthPx - resultWidth)) {
        startX = screenWidthPx - resultWidth - totalWidth
    }

    viewModel.mahjongList.forEachIndexed { index, mahjongModel ->
        drawPai(drawScope, originalImage, mahjongModel, startX + index * width, startY)
    }
}

/**
 * 绘制出牌列表
 */
private fun drawPaiOutList(
    drawScope: DrawScope,
    originalImage: Bitmap,
    viewModel: MahjongViewModel,
    screenWidthPx: Int,
    screenHeightPx: Int
) {
    val totalWidth = viewModel.mahjongOutList.sumOf { it.drawInfo.srcRect.width() }
    val width = viewModel.mahjongOutList.firstOrNull()?.drawInfo?.srcRect?.width()?:0
    val height = viewModel.mahjongOutList.firstOrNull()?.drawInfo?.srcRect?.height()?:0


    // 水平居中排列
    val startX =  (screenWidthPx - totalWidth) / 2
    val startY = (screenHeightPx - height) / 2
    viewModel.mahjongOutList.forEachIndexed { index, mahjongModel ->
        drawPai(drawScope, originalImage, mahjongModel, startX + index * width, startY)
    }
}

private fun drawPai(drawScope: DrawScope, originalImage: Bitmap, mahjongModel:MahjongModel, x:Int, y:Int) {
    // 要截取的区域
    val srcRect = mahjongModel.drawInfo.srcRect
    val dstRect = Rect(x, y, x + mahjongModel.drawInfo.srcRect.width(), y + mahjongModel.drawInfo.srcRect.height()) // 绘制到画布上的目标区域

    mahjongModel.drawInfo.dstRect = dstRect
    // 创建一个画笔
    val paint = Paint()
    // 在Canvas上绘制截取的图像
    drawScope.drawIntoCanvas { canvas ->
        if (mahjongModel.isSelected.value) {
            val top = y - mahjongModel.drawInfo.srcRect.height() / 2
            canvas.nativeCanvas.drawBitmap(originalImage, srcRect, Rect(x, top, x + mahjongModel.drawInfo.srcRect.width(), top + mahjongModel.drawInfo.srcRect.height()) , paint)
        } else {
            canvas.nativeCanvas.drawBitmap(originalImage, srcRect, dstRect, paint)
        }
    }
}


@Composable
private fun ShowResult(modifier:Modifier = Modifier,title:String = "回答正确", answer:String = "应该打 5 万",content:String = "不打4条，因为破坏了 3334条 可以进张 245条 3门11 张搭子\n" +
        "不打3条，虽然打 3筒 可以让 556万 和 33条 形成 2对半牌形，34 条作为双头搭子\n" +
        "打出5万，利用 36筒 2门6张的机会，可以听胡在 56万 的双面搭子上", isCorrect:Boolean = true, onConfirm:()->Unit = {}) {

    val styledText = buildAnnotatedString {
        withStyle(style = SpanStyle(color = Color.Blue, fontSize = 18.sp)) {
            append(answer + "\n")
        }
        withStyle(style = SpanStyle(color = Color.Black, fontSize = 18.sp)) {
            append(content)
        }
    }

    // 创建一个滚动状态
    Box(modifier = modifier
        .background(color = Color.White)
        .width(250.dp)
        .fillMaxHeight()) {
        Column(modifier = Modifier.verticalScroll(rememberScrollState())) {
            Spacer(modifier = Modifier.height(30.dp))
            Text(styledText)
            Spacer(modifier = Modifier.height(40.dp))
        }
        ElevatedButton(modifier = Modifier
            .padding(start = 15.dp)
            .align(Alignment.BottomEnd), onClick = {
            onConfirm.invoke()
        }) {
            // 按钮文本
            Text("下一题")
        }
        Text(title, color = if (isCorrect) Color(0xff6AAB73) else Color.Red, modifier = Modifier
            .fillMaxWidth()
            .background(color = Color(0xcfffffff))
            .padding(all = 5.dp))
    }
}
